import { IDomEditor } from '@wangeditor/editor';
import { IExtendConfig } from './interface';
import { replaceSymbols } from '../../utils/tool';

const getMentionConfig = (editor: IDomEditor) => {
  const { EXTEND_CONF } = editor.getConfig();
  const { mentionConfig } = EXTEND_CONF as IExtendConfig;
  return mentionConfig;
};

const insertMention = (
  editor: IDomEditor,
  name: string,
  url: string,
  target: string,
  insertMentionType: string = 'keyboard',
) => {
  // console.log('插入的文本类型：',target)
  const mentionNode = {
    type: 'mention', // 必须是 'mention'
    value: `${name}`,
    url: url,
    target: target,
    typeLink: target,
    info: {},
    // children: [{ text: '' }], // 必须有一个空 text 作为 children
    children: [{ text: replaceSymbols(name) }],
  };
  // console.log('插入提醒的类型', insertMentionType);
  editor.restoreSelection(); // 恢复选区
  // 如果是输入法调起，需要删除前一个字符  如果是点击调起，就不需要
  // 输入法调起 handleType = 'keyboard'  点击调起 handleType = 'click'
  if (insertMentionType === 'keyboard') {
    editor.deleteBackward('character'); // 删除 '@'或者'#'
  }
  // 如果是菜单栏输入，只不需要，直接插入即可
  // editor.deleteBackward('character'); // 删除 '@'

  editor.insertNode(mentionNode); // 插入 mention
  editor.insertFragment([{ text: ' ' }]); // 插入空格
  editor.move(1); // 移动光标
};
export { insertMention, getMentionConfig };
